const fs = require('fs')
const multer = require("multer");
const path = require('path');
const image_type_arr1 = ["image/jpeg", "image/png", "image/webp", "image/jpg", "image/gif", "image/heic"];
const image_originalname_arr1 = [".jpeg", ".png", ".webp", ".jpg", ".gif", ".heic"];

//video
const allowedMimesVideo = ["video/mp4", 'video/avi', 'video/mov'];
const image_originalname_arr = [".mp4", '.avi', '.mov'];

/**
 * use全局参数
 * global.maxFileSize=  400 * 1024 * 1024; //视频文件大小
	global.maxImageFileSize=50 * 1024 * 1024; //图片文件大小
*/
const fileFilter = (req, file, cb) => {
	const extension = path.extname(file.originalname).toLowerCase();
	const mimetype = file.mimetype;
	let file_type_code = image_type_arr1.indexOf(mimetype);
	let file_originalname_code = image_originalname_arr1.indexOf(extension);
	if (file_type_code == -1 || file_originalname_code == -1) {
		cb('error file type', false);
	} else {
		cb(null, true);
	}
}

// 设置Multer存储配置
const storage = multer.diskStorage({
	destination: (req, file, cb) => {
		const uploadPath = path.join(rootDirname, 'public/imgs');
		if (!fs.existsSync(uploadPath)) {
			fs.mkdirSync(uploadPath);
		}
		cb(null, uploadPath);
	},
	filename: (req, file, cb) => {
		const uniqueSuffix = Date.now() + '_' + Math.round(Math.random() * 1E9);
		const extname = path.extname(file.originalname);
		cb(null, uniqueSuffix + extname);
	}
});
/**
 * limits
 *    fieldNameSize - 字段名最大尺寸。默认值：100 bytes
       fieldSize - 字段值最大尺寸。默认值：1MB
       fields - 非文件字段的最大数量。默认值：Infinity
	*** fileSize - multipart 表单中，[文件的最大尺寸]。默认值：Infinity
       files - multipart 表单中，文件最大数量。默认值：Infinity
       parts - multipart 表单中，最大组件(fields+files)数量。默认值：Infinity
 * 
*/
const upload_iamge = multer({
	storage: storage,
	limits: {
		fileSize: maxImageFileSize
	},
	fileFilter
});



// 设置Multer存储配置
const storageVideo = multer.diskStorage({
	destination: (req, file, cb) => {
		const uploadPath = path.join(rootDirname, 'public/videos');
		if (!fs.existsSync(uploadPath)) {
			fs.mkdirSync(uploadPath);
		}
		cb(null, uploadPath);
	},
	filename: (req, file, cb) => {
		const uniqueSuffix = Date.now() + '_' + Math.round(Math.random() * 1E9);
		const extname = path.extname(file.originalname);
		cb(null, uniqueSuffix + extname);
	}
});
const fileFilterVideo = (req, file, cb) => {
	const extension = path.extname(file.originalname).toLowerCase();
	const mimetype = file.mimetype;
	let file_type_code = allowedMimesVideo.indexOf(mimetype);
	let file_originalname_code = image_originalname_arr.indexOf(extension);
	if (file_type_code == -1 || file_originalname_code == -1) {
		cb('error file type', false);
	} else {
		cb(null, true);
	}
}
const upload_video = multer({
	// dest: "public/videos",
	storage: storageVideo,
	limits: {
		fileSize: maxFileSize
	},
	fileFilter: fileFilterVideo
	
})
module.exports = {
	upload_iamge,
	upload_video
};